///////////////////////////////////////////////////////////
// 
//  MySphere.cpp
// 
//  Authors:  Jeremy Bennett
//
///////////////////////////////////////////////////////////

// Local Includes
#include "stdafx.h"
#include "MySphere.h"
#include "MyContext.h"

// SDL Includes
#include <SDL_opengl.h>

// Bullet Includes
#include <BulletCollision/CollisionShapes/btSphereShape.h>
#include <LinearMath/btDefaultMotionState.h>

// System Includes

MySphere::MySphere( const btScalar   fRadius,
                    const btVector3 &vOrigin, 
                    const btScalar   fMass )
: MyShape() 
{
    _eType = my_sphere;

    _pShp = new btSphereShape(fRadius);
    
    btTransform colTran;
	colTran.setIdentity();
    colTran.setOrigin(vOrigin);

    btVector3 locInertia(0,0,0);
    if ( fMass != 0 ) {
        _pShp->calculateLocalInertia(fMass,locInertia);
    }

    btDefaultMotionState* pMotState = new btDefaultMotionState(colTran);
    btRigidBody::btRigidBodyConstructionInfo rbInfo(fMass,pMotState,_pShp,locInertia);
	rbInfo.m_friction = 2.0f;
	rbInfo.m_angularDamping = 1.0f;
    setupRigidBody(rbInfo);

    if ( fMass != 0 ) {
	    setLinearFactor(btVector3(1,1,1));
	    setAngularFactor(btVector3(0,0,1));
	    setCcdMotionThreshold(1.);
	    setCcdSweptSphereRadius(0.2f);
    }
}

MySphere::~MySphere() 
{
}

bool 
MySphere::render( MyContext *ctx )
{

    btScalar	m[16];

    btDefaultMotionState *pMotState = (btDefaultMotionState*)getMotionState();
    pMotState->m_graphicsWorldTrans.getOpenGLMatrix(m);

    glColor4f( _vCol[0], _vCol[1], _vCol[2], _vCol[3] );

#if 1
    glPushMatrix(); 
	glMultMatrixf(m);

    const btSphereShape* sphereShape = static_cast<const btSphereShape*>(_pShp);
	float radius = sphereShape->getMargin();//radius doesn't include the margin, so draw with margin

    int lats=10, longs=10;
    int i, j;
	for(i = 0; i <= lats; i++) {
		btScalar lat0 = SIMD_PI * (-btScalar(0.5) + (btScalar) (i - 1) / lats);
		btScalar z0  = radius * sin(lat0);
		btScalar zr0 = radius * cos(lat0);

		btScalar lat1 = SIMD_PI * (-btScalar(0.5) + (btScalar) i / lats);
		btScalar z1  = radius * sin(lat1);
		btScalar zr1 = radius * cos(lat1);

		glBegin(GL_QUAD_STRIP);
		for(j = 0; j <= longs; j++) {
			btScalar lng = 2 * SIMD_PI * (btScalar) (j - 1) / longs;
			btScalar x = cos(lng);
			btScalar y = sin(lng);

			glNormal3f(x * zr0, y * zr0, z0);
			glVertex3f(x * zr0, y * zr0, z0);
			glNormal3f(x * zr1, y * zr1, z1);
			glVertex3f(x * zr1, y * zr1, z1);
		}
		glEnd();
	}

    glPopMatrix();
#endif

    return true;
}